<template>
  <div class="dashboard-editor-container">
    <div class="container">
      <div class="searchData">
        <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
      </div>
      <div ref="chart" class="wordContainer"></div>
    </div>
  </div>
</template>

<script>
import "echarts-wordcloud";
import connsearch from "@/components/connSearch";
import Cookies from "js-cookie";
import { parseTime } from "@/utils/index.js";
import { Word_Count_URLS } from "./api/request";
import { noTokenRequest } from "@/api/material";
export default {
  name: "Wordfrequency",
  components: {
    connsearch
  },
  data() {
    let that = this;
    return {
      dateRange: ["2023-01-01", "2023-12-31"],
      color: "",
      searchform: {},
      knowledgeIP: "",
      formOptions: [
        {
          col: 8,
          label: "时间范围",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: "daterange",
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        }
      ],
      wordCloudColorsDark: [
        "#FFFFFF",
        "#E0E0E0",
        "#B0E0E6",
        "#ADD8E6",
        "#98FB98",
        "#FFD700",
        "#FFA07A",
        "#FF69B4",
        "#FF6347",
        "#DDA0DD",
        "#F0F8FF",
        "#E6E6FA",
        "#F5F5DC",
        "#FFFACD",
        "#FFE4E1",
        "#00CED1",
        "#7FFFD4",
        "#F08080",
        "#FFB6C1",
        "#FFDEAD"
      ],
      wordCloudColorsLight: [
        "#000000",
        "#333333",
        "#1C2526",
        "#2F4F4F",
        "#483D8B",
        "#4682B4",
        "#2E8B57",
        "#556B2F",
        "#8B4513",
        "#A52A2A",
        "#B22222",
        "#DC143C",
        "#C71585",
        "#9932CC",
        "#4B0082",
        "#FF4500",
        "#DAA520",
        "#8A2BE2",
        "#228B22",
        "#191970"
      ],
      wordFreqData: {}
    };
  },
  created() {
    let endTime = new Date(new Date().setHours(0, 0, 0, 0));
    let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
    let arr = [parseTime(startTime), parseTime(endTime)]; // 将第二个元素也设置为格式化后的 endTime
    this.formOptions.map((item) => {
      if (item.label === "时间范围") {
        item.initValue = arr;
      }
    });
    this.$set(this.searchform, "timeRange", arr);
    this.getwordFreqData();
  },
  mounted() {
    this.color = localStorage.getItem("isNightMode");
    this.initChart();
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chart;
      const myChart = this.$echarts.init(chartDom);

      let data = Object.entries(this.wordFreqData).map(([name, value]) => ({
        name,
        value
      }));

      //当词条不够100时，重复添加数据，填充空白区域
      while (data.length > 0 && data.length < 100) {
        data = [...data, ...data];
      }

      const option = {
        tooltip: {
          formatter: "{b}: {c} 次"
        },
        series: [
          {
            type: "wordCloud",
            shape: "rectangle", // 改为 square，避免圆形留白
            gridSize: 5, // 减小词间距
            sizeRange: [30, 120], // 增大字体范围
            rotationRange: [-90, 90], // 更灵活的旋转角度
            width: "99%", // 强制词云宽度占满容器
            height: "99%", // 强制词云高度占满容器
            data,
            textStyle: {
              color: () => {
                return this.color === "night"
                  ? this.wordCloudColorsDark[Math.floor(Math.random() * this.wordCloudColorsDark.length)]
                  : this.wordCloudColorsLight[Math.floor(Math.random() * this.wordCloudColorsLight.length)];
              }
            }
          }
        ]
      };

      myChart.setOption(option);

      // 动态调整词云大小
      this.$nextTick(() => {
        myChart.resize();
      });

      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    search(val) {
      this.searchform = { ...val };
      this.getwordFreqData();
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), parseTime(endTime)]; // 将第二个元素也设置为格式化后的 endTime
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "时间范围") {
          item.initValue = arr;
        }
        return item;
      });
      this.searchform = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$refs.connsearch.addInitValue();
      this.getwordFreqData();
    },
    async getwordFreqData() {
      if (this.checkHasIP()) {
        const data = {
          StartDate: this.searchform?.timeRange?.[0]?.split(" ")?.[0] || "",
          EndDate: this.searchform?.timeRange?.[1]?.split(" ")?.[0] || ""
        };
        const res = await noTokenRequest(Word_Count_URLS, data);
        if (res.Status.StatusCode === 0) {
          this.wordFreqData = res.Data;
          this.initChart();
        }
      }
    },
    checkHasIP() {
      this.knowledgeIP = localStorage.getItem("KnowledgeIP");
      if (this.knowledgeIP) {
        return true;
      } else {
        this.$message.error("请先配置知识库地址");
        return false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  background: #fff;
  border: 1px solid #dcdfe6;
  padding: 20px;
}

.wordContainer {
  width: 100%;
  height: calc(100vh - 315px);
}

.searchData {
  background: #fff;
  padding: 20px;
}

.night {
  .container {
    background: #303445;
    border: none;
  }
  .searchData {
    background: #303445;
  }
}
</style>
